package org.fone.service.impl;

import cn.hutool.json.JSONObject;
import org.fone.mapper.TableMapper;
import org.fone.pojo.TableField;
import org.fone.pojo.Table;
import org.fone.pojo.TableInfo;
import org.fone.service.TableService;
import org.fone.utils.task.TaskCreator;
import org.fone.utils.task.TaskRunner;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.sql.Timestamp;
import java.util.*;

@Service
public class TableServiceImpl implements TableService {
    private final TableMapper tableMapper;

    public TableServiceImpl(TableMapper tableMapper) {
        this.tableMapper = tableMapper;
    }

    @Override
    public List<TableInfo> listTable() {
        try {
            List<TableInfo> list = tableMapper.listTable();
            //查询列名
            list.forEach(tableInfo ->
                    tableInfo.setTableFields(
                            listTableField(tableInfo.getTable_name())
                    )
            );
            return list;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<TableField> listTableField(String tabName) {
        if (ObjectUtils.isEmpty(tabName)) return null;
        try {
            //获取列名
            List<TableField> tableFields = tableMapper.listTableFieldByTableName(tabName);
            if (ObjectUtils.isEmpty(tabName)) return null;
            tableFields.forEach(tableField -> {
                String type = tableField.getData_type().toLowerCase();
//                System.out.println("type = " + type);
                if (type.contains("int")||type.matches(".*((float)|(double)|(decimal)).*")) type = "number";
                else if (type.matches(".*((date)|(time)|(year)).*")) type = "date";
                else type = "str";
                tableField.setData_type(type);
//                System.out.println("type2 = " + type);
            });
//            System.out.println(tableFields);
            return tableFields;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Table readTable(String tabName) {
        //获取列名
        List<TableField> tableFields = listTableField(tabName);
        try {
            if (ObjectUtils.isEmpty(tabName)) return null;
            //获取所有行(表内容）,并将信息封装
            return new Table(tabName,tableFields,tableMapper.listLineByTableName(tabName));
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public JSONObject dataStream(JSONObject data) {
        TaskRunner taskRunner = new TaskCreator(data).getTaskRunner(this);
        int flag = taskRunner.check();
        JSONObject res = new JSONObject();
        if (flag!=0) return res.set("flag",flag).set("msg","参数检查不通过");
        flag = taskRunner.run();
        return res.set("flag",flag).set("msg","已运行").set("data",taskRunner.getResultData());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean createTable(Table table) {
        for (TableField field : table.getTableFields()) {
            if (field.getData_type() == null || !field.getData_type().matches("(str)|(date)|(number)")) {
                return false;
            }
        }
        try {
            tableMapper.createTable(table.getTableName(), table.getTableFields());
            List<List<Object>> content = new ArrayList<List<Object>>();
            List<Object> temp = null;
            LinkedList<Map<String, Object>> lines = table.getTableLines();
            List<TableField> tableFields = table.getTableFields();
            for (Map<String, Object> line : lines) {
                System.out.println(line);
                temp = new ArrayList<Object>();
                for (TableField tableField : tableFields) {
                    if (tableField.data_type.contains("date")) {
                        Timestamp date = (Timestamp) line.get(tableField.column_name);
                        temp.add(date);
                        System.out.println("date = " + date);
                    } else {
                        temp.add(line.get(tableField.column_name));
                    }
                }
                content.add(temp);
            }
            insertInfoToTable(table.getTableName(), content);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertInfoToTable(String tableName, List<List<Object>> contents) {
        return tableMapper.insertInfoToTable(tableName,contents);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean findTableCountByTableName(String tabName) {
        return tableMapper.findTableCountByTableName(tabName) == 1;
    }

}
